<template>
  <div class="form-box">
    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="150px" size="large">
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.name" maxlength="10" show-word-limit />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname" maxlength="15" show-word-limit />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker v-model="form.birthday" type="date" format="YYYY 年 MM 月 DD 日" value-format="YYYY/MM/DD"
          placeholder="请选择出生日期" style="width: 100%" />
      </el-form-item>
      <el-form-item label="角色分配" prop="power">
        <el-select v-model="form.power" placeholder="请选择角色" style="width: 100%">
          <el-option label="普通用户" value="user" />
          <el-option label="系统管理员" value="admin" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" :rows="4" resize="none" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">保存</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { addAccount, accountInfo, updateAccount } from '@/api/api'
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
const router = useRouter()
const route = useRoute()

const ruleFormRef = ref<FormInstance>()

let loading = ref(false)

// 表单
let form = reactive({
  account: '',
  password: '',
  name: '',
  nickname: '',
  sex: 'male',
  birthday: '',
  power: '',
  remark: ''
})

const id = route.params.id || null

// 表单验证
const rules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '账号的长度在2到20个字符之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码的长度在6到20个字符之间', trigger: 'blur' },
  ],
  sex: [
    {
      required: true,
      message: '请选择性别',
      trigger: 'change',
    },
  ],
  birthday: [
    {
      type: 'date',
      required: true,
      message: '请选择出生日期',
      trigger: 'change',
    },
  ],
  power: [
    {
      required: true,
      message: '请分配权限',
      trigger: 'change',
    },
  ],
})

// 提交信息
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      if (id) {
        let formData = {
          ...form,
          id
        }
        // 编辑账号
        updateAccount(formData).then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('更新成功')
            router.push({
              name: 'account'
            })
          } else {
            ElMessage.error('更新失败')
          }
        }).finally(() => {
          loading.value = false
        })
      } else {
        let formData = {
          ...form
        }
        // 新增账号
        addAccount(formData).then((res: any) => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            router.push({
              name: 'account'
            })
          } else {
            ElMessage.error('新增失败')
          }
        }).finally(() => {
          loading.value = false
        })
      }
    } else {
      ElMessage.error('请正确填写表单')
    }
  })
}

onMounted(() => {
  if (id) {
    accountInfo(id).then((res: any) => {
      form.account = res.result.account
      form.password = res.result.password
      form.name = res.result.name
      form.nickname = res.result.nickname
      form.sex = res.result.sex
      form.birthday = res.result.birthday
      form.power = res.result.power
      form.remark = res.result.remark
    })
  }
})
</script>

<style lang="scss" setup>
.form-box {
  width: 600px;
  margin-top: 30px;
}
</style>